// 选中文本对话

//选中文本对话记忆
let selectedTextDialogHistory = [];

//选中文本显示按钮
document.addEventListener('mouseup', function (event) {
    const selection = window.getSelection();
    let button = document.getElementById('popupButton');

    if (!button) {
        button = document.createElement('button');
        button.id = 'popupButton';
        button.style.backgroundImage = `url(chrome-extension://${chrome.runtime.id}/images/16.png)`;
        document.body.appendChild(button);

        button.addEventListener('click', function () {
            showCustomDialog(selection.toString().trim());
        });
    }

    if (!selection.isCollapsed && selection.toString().trim() !== '') {
        const range = selection.getRangeAt(0);
        const rect = range.getBoundingClientRect();

        button.style.top = (rect.top + window.scrollY - 40) + 'px';
        button.style.left = (rect.right + window.scrollX) + 'px';
        button.style.display = 'block';
    } else {
        button.style.display = 'none';
    }
});

//鼠标点击按钮或按钮外图标显示类型
document.addEventListener('mousedown', function (event) {
    const button = document.getElementById('popupButton');
    const dialog = document.getElementById('customDialog');
    if (button && !button.contains(event.target)) {
        button.style.display = 'none';
    }
    if (dialog && !dialog.contains(event.target)) {
        dialog.style.display = 'none';
        const mainContent = document.getElementById('mainContent');
        if (mainContent) {
            mainContent.innerHTML = '<h3>解释</h3>';
        }
        const aiAnswerElement = document.getElementById('aiAnswer');
        if (aiAnswerElement) {
            aiAnswerElement.textContent = '正在获取解释...';
        }
    }
});

let currentPort = null;

//显示选中文本问答弹窗
async function showCustomDialog(selectedText) {
    let dialog = document.getElementById('customDialog');
    if (!dialog) {
        dialog = document.createElement('div');
        dialog.id = 'customDialog';
        dialog.innerHTML = `
            <style>
                #customDialog .main-content p {
                    text-indent: 2em;
                    margin-bottom: 1em;
                }
                #customDialog .divider {
                    border: 0;
                    border-top: 1px solid #ccc;
                    margin: 10px 0;
                }
            </style>
            <div class="dialog-content">
                <div class="main-content" id="mainContent">
                    <h3>解释</h3>
                </div>
                <div class="input-container">
                    <input type="text" id="userQuestion" placeholder="有什么问题尽管问我" autocomplete="off">
                    <button id="sendButton" style="background-image: url(chrome-extension://${chrome.runtime.id}/images/send-icon.png)"></button>
                    <button id="abortButton" style="display: none; background-image: url(chrome-extension://${chrome.runtime.id}/images/stop-icon.png)"></button>
                </div>
            </div>
        `;
        document.body.appendChild(dialog);

        const sendButton = document.getElementById('sendButton');
        const abortButton = document.getElementById('abortButton');
        const userQuestionInput = document.getElementById('userQuestion');

        function sendMessage() {
            const userQuestion = userQuestionInput.value.trim();
            if (userQuestion !== '') {
                addNewQuestion(userQuestion);
                getAIAnswer(userQuestion);
                userQuestionInput.value = '';
                userQuestionInput.placeholder = '有什么问题尽管问我';
            }
        }

        sendButton.addEventListener('click', sendMessage);

        userQuestionInput.addEventListener('keydown', function (event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                sendMessage();
            }
        });

        abortButton.addEventListener('click', function () {
            if (currentPort) {
                currentPort.disconnect();
                currentPort = null;
                toggleButtons(false);
            }
        });
    }

    dialog.style.display = 'block';
    addNewQuestion(selectedText);
    await getAIAnswer(selectedText);
}

//添加新问题
function addNewQuestion(question) {
    const mainContent = document.getElementById('mainContent');

    const divider = document.createElement('hr');
    divider.className = 'divider';
    mainContent.appendChild(divider);

    const questionElement = document.createElement('p');
    questionElement.className = 'user-question';
    questionElement.textContent = `问题: ${question}`;
    mainContent.appendChild(questionElement);

    const answerElement = document.createElement('p');
    answerElement.className = 'ai-answer';
    answerElement.textContent = '正在获取解释...';
    mainContent.appendChild(answerElement);

    selectedTextDialogHistory.push({ question: question, answer: '' });

    return answerElement;
}

//获取大模型返回答案
async function getAIAnswer(text) {
    console.log('Sending request to background script...');

    toggleButtons(true);

    const mainContent = document.getElementById('mainContent');
    const aiAnswerElement = mainContent.lastChild;

    try {
        currentPort = chrome.runtime.connect({ name: "aiAnswer" });
        currentPort.postMessage({ action: "getAIAnswer", text: text, context: selectedTextDialogHistory });

        let fullResponse = '';
        const pattern = /"content":"(.*?)(?<!\\)"/;
        currentPort.onMessage.addListener(function (msg) {
            if (msg.type === 'chunk') {
                const match = pattern.exec(msg.data);

                if (match) {
                    const content = JSON.parse(`"${match[1]}"`);
                    fullResponse += content;

                    const formattedAnswer = formatAnswer(fullResponse);

                    aiAnswerElement.innerHTML = formattedAnswer;
                    aiAnswerElement.scrollTop = aiAnswerElement.scrollHeight;

                    //更新最后答案到记忆
                    selectedTextDialogHistory[selectedTextDialogHistory.length - 1].answer = fullResponse;
                }
            } else if (msg.type === 'end') {
                console.log('Stream ended');
                toggleButtons(false);
                aiAnswerElement.scrollTop = 0;

            } else if (msg.type === 'error') {
                console.error('Error:', msg.error);
                aiAnswerElement.textContent = '无法获取解释，请稍后再试。';
                toggleButtons(false);
            }
        });
    } catch (error) {
        console.error('Error calling background script:', error);
        aiAnswerElement.textContent = '发生错误，请稍后再试。';
        toggleButtons(false);
    }
}

//发送中止按钮转换
function toggleButtons(isStreaming) {
    const sendButton = document.getElementById('sendButton');
    const abortButton = document.getElementById('abortButton');
    if (isStreaming) {
        sendButton.style.display = 'none';
        abortButton.style.display = 'block';
    } else {
        sendButton.style.display = 'block';
        abortButton.style.display = 'none';
    }
}

// 格式化大模型返回代码
function formatAnswer(text) {
    let formatted = text
        .replace(/\n\n+/g, '</p><p>')
        .replace(/\n/g, '<br>');

    formatted = formatted.replace(/```([\s\S]*?)```/g, function (match, code) {
        return `<code>${code.trim()}</code>`;
    });

    formatted = formatted.replace(/`([^`]+)`/g, '$1');

    formatted = formatted.replace(/\*\*([^\*]+)\*\*/g, '<strong>$1</strong>');

    formatted = formatted.replace(/\*([^*]+)\*/g, '<em>$1</em>');

    formatted = formatted.replace(/__([^_]+)__/g, '<u>$1</u>');

    formatted = formatted.replace(/~~([^~]+)~~/g, '<del>$1</del>');

    formatted = formatted.replace(/^(#{1,6})\s*(.+)$/gm, function (match, hashes, title) {
        const level = hashes.length;
        return `<h${level}>${title}</h${level}>`;
    });

    if (!formatted.startsWith('<p>')) {
        formatted = '<p>' + formatted;
    }
    if (!formatted.endsWith('</p>')) {
        formatted += '</p>';
    }

    return formatted;
}



//全局问答

//全局对话一个记忆
let globalDialogHistory = [];

document.addEventListener('DOMContentLoaded', function () {
    try {
        // 灰色覆盖层
        let overlay = document.createElement('div');
        overlay.id = 'extension-overlay';
        overlay.style.display = 'none';
        document.body.appendChild(overlay);

        // 全局按钮
        let button = document.createElement('button');
        button.id = 'unique-custom-button';
        button.innerHTML = '<img src="chrome-extension://' + chrome.runtime.id + '/images/48.png" alt="Extension Icon">';
        document.body.appendChild(button);

        // 弹窗1
        let dialog1 = document.createElement('div');
        dialog1.id = 'custom-dialog-1';
        dialog1.style.display = 'none';
        dialog1.innerHTML = `
            <div class="dialog-header">
                <input type="text" id="userQuestion1" placeholder="有什么问题尽管问我" autocomplete="off">
            </div>
            <div id="dialog-content"></div>
            <div class="dialog-footer"> 
                <button class="dialog-item" id="summarize-btn">                
                    <span>总结全文</span>
                </button>
                <button id="send-btn1" style="background-image: url(chrome-extension://${chrome.runtime.id}/images/send-icon.png);"></button>
            </div>
        `;
        document.body.appendChild(dialog1);

        // 弹窗2
        let dialog2 = document.createElement('div');
        dialog2.id = 'custom-dialog-2';
        dialog2.style.display = 'none';
        dialog2.innerHTML = `
            <div id="dialog-content-2" class="main-content"></div>
            <div class="dialog-footer">
                <div class="input-container">
                    <input type="text" id="user-input" placeholder="有什么问题尽管问我">
                    <button id="send-btn2" style="background-image: url(chrome-extension://${chrome.runtime.id}/images/send-icon.png);"></button>
                    <button id="stop-btn2" style="display: none; background-image: url(chrome-extension://${chrome.runtime.id}/images/stop-icon.png)"></button>
                </div>
            </div> 
        `;
        document.body.appendChild(dialog2);

        // 点击按钮显示弹窗1和覆盖层
        button.addEventListener('click', function () {
            overlay.style.display = 'block';
            dialog1.style.display = 'block';
        });

        // 点击弹窗外覆盖层关闭弹窗
        overlay.addEventListener('click', function (e) {
            if (e.target === overlay) {
                dialog1.style.display = 'none';
                dialog2.style.display = 'none';
                overlay.style.display = 'none';
            }
        });

        // 总结全文按钮
        document.getElementById('summarize-btn').addEventListener('click', function () {
            dialog1.style.display = 'none';
            dialog2.style.display = 'flex';
            const dialogContent2 = document.getElementById('dialog-content-2');
            const content = extractMainContent();
            sendToModel('请总结以下文本内容：\n\n' + content, content, true);
        });

        // 全局弹窗1发送按钮
        document.getElementById('send-btn1').addEventListener('click', function () {
            const question = document.getElementById('userQuestion1').value;
            document.getElementById('userQuestion1').value = '';
            if (question === '') {
                return; // 输入为空，不发送信息
            }
            dialog1.style.display = 'none';
            dialog2.style.display = 'flex';
            const content = extractMainContent();
            sendToModel(question, content);
        });

        // 全局弹窗2发送按钮
        document.getElementById('send-btn2').addEventListener('click', function () {
            const question = document.getElementById('user-input').value;
            document.getElementById('user-input').value = '';
            if (question === '') {
                return; // 输入为空，不发送信息
            }
            const content = extractMainContent();
            sendToModel(question, content);
        });

        // 全局弹窗2中止按钮
        document.getElementById('stop-btn2').addEventListener('click', function () {
            if (currentPort) {
                currentPort.disconnect();
                currentPort = null;
                toggleButtonsGlobal(false);
                const aiAnswerElement = document.querySelector('#dialog-content-2 .ai-answer:last-of-type');
                aiAnswerElement.innerHTML += '（已中止）';
            }
        });

        //将问题和内容发送到模型。如果isSummarize为真，则在全局添加新的问题'总结全文'；
        //否则，添加新的问题question。然后，获取AI的答案并添加到aiAnswerElement中
        // async function sendToModel(question, content, isSummarize = false) {
        //     console.log('发送到大模型的问题:', question);
        //     if (content) {
        //         console.log('额外内容:', content);
        //     }

        //     let aiAnswerElement;
        //     if (isSummarize) {
        //         aiAnswerElement = addNewQuestionGlobal('总结全文');
        //     } else {
        //         aiAnswerElement = addNewQuestionGlobal(question);
        //     }

        //     if (aiAnswerElement) {
        //         await getAIAnswerGlobal(question, content, aiAnswerElement);
        //     }
        // }
        async function sendToModel(question, content, isSummarize = false) {
            console.log('发送到大模型的问题:', question);
            if (content) {
                console.log('额外内容:', content);
            }

            let aiAnswerElement;
            if (isSummarize) {
                aiAnswerElement = addNewQuestionGlobal('总结全文');
                question = `请总结以下文本内容：\n\n${content}`;
            } else {
                aiAnswerElement = addNewQuestionGlobal(question);
                question = `根据以下网页内容回答问题：\n\n${content}\n\n问题：${question}`;
            }

            if (aiAnswerElement) {
                await getAIAnswerGlobal(question, content, aiAnswerElement);
            }
        }

        //提取网页主要内容的函数。它首先尝试使用jQuery来获取可能的内容选择器
        //如果这些选择器都没有找到内容，就使用body作为默认的选择器。然后，它会限制文本长度，防止超过大模型的输入限制
        function extractMainContent() {
            let mainContent = '';
            if (typeof jQuery !== 'undefined') {
                // 使用更复杂的选择器来尝试获取主要内容
                const possibleContentSelectors = [
                    'article',
                    '.post-content',
                    '.entry-content',
                    '#main-content',
                    '.main-content',
                    'main',
                    '.content'
                ];

                for (let selector of possibleContentSelectors) {
                    const content = jQuery(selector).text().trim();
                    if (content.length > mainContent.length) {
                        mainContent = content;
                    }
                }

                // 如果上面的选择器都没有找到内容，就使用body
                if (mainContent === '') {
                    mainContent = jQuery('body').text().trim();
                }
            } else {
                console.warn('jQuery 未加载');
                // fallback to vanilla JavaScript
                mainContent = document.body.innerText.trim();
            }

            // 限制文本长度，防止超过大模型的输入限制
            const maxLength = 4000; // 你可能需要根据实际情况调整这个值
            if (mainContent.length > maxLength) {
                mainContent = mainContent.substring(0, maxLength) + '...（内容已截断）';
            }

            return mainContent;
        }

        //添加新问题
        function addNewQuestionGlobal(question) {
            const mainContent = document.getElementById('dialog-content-2');
            if (!mainContent) {
                console.error('Cannot find dialog-content-2');
                return null;
            }

            if (mainContent.children.length > 0) {
                const hr = document.createElement('hr');
                mainContent.appendChild(hr);
            }

            const questionElement = document.createElement('p');
            questionElement.className = 'user-question';
            questionElement.textContent = `问题: ${question}`;
            mainContent.appendChild(questionElement);

            const answerElement = document.createElement('p');
            answerElement.className = 'ai-answer';
            answerElement.textContent = '正在获取解释...';
            mainContent.appendChild(answerElement);

            mainContent.scrollTop = mainContent.scrollHeight;

            globalDialogHistory.push({ question: question, answer: '' });

            return answerElement;
        }

        //获取全局对话中大模型返回的答案
        async function getAIAnswerGlobal(text, pageContent, aiAnswerElement) {
            console.log('Sending request to background script...');

            toggleButtonsGlobal(true);

            try {
                currentPort = chrome.runtime.connect({ name: "aiAnswer" });
                currentPort.postMessage({
                    action: "getAIAnswer",
                    text: text,
                    pageContent: pageContent,
                    context: globalDialogHistory
                });

                let fullResponse = '';
                const pattern = /"content":"(.*?)(?<!\\)"/;
                currentPort.onMessage.addListener(function (msg) {
                    if (msg.type === 'chunk') {
                        const match = pattern.exec(msg.data);

                        if (match) {
                            const content = JSON.parse(`"${match[1]}"`);
                            fullResponse += content;

                            const formattedAnswer = formatAnswer(fullResponse);

                            if (aiAnswerElement) {
                                aiAnswerElement.innerHTML = formattedAnswer;
                                aiAnswerElement.scrollTop = aiAnswerElement.scrollHeight;
                            }

                            // Update the last answer in the history
                            globalDialogHistory[globalDialogHistory.length - 1].answer = fullResponse;
                        }
                    } else if (msg.type === 'end') {
                        console.log('Stream ended');
                        toggleButtonsGlobal(false);
                        if (aiAnswerElement) {
                            aiAnswerElement.scrollTop = 0;
                        }
                    } else if (msg.type === 'error') {
                        console.error('Error:', msg.error);
                        if (aiAnswerElement) {
                            aiAnswerElement.textContent = '无法获取解释，请稍后再试。';
                        }
                        toggleButtonsGlobal(false);
                    }
                });
            } catch (error) {
                console.error('Error calling background script:', error);
                if (aiAnswerElement) {
                    aiAnswerElement.textContent = '发生错误，请稍后再试。';
                }
                toggleButtonsGlobal(false);
            }
        }

        //全局发送中止按钮转换
        function toggleButtonsGlobal(isStreaming) {
            const sendButton = document.getElementById('send-btn2');
            const abortButton = document.getElementById('stop-btn2');
            if (sendButton && abortButton) {
                if (isStreaming) {
                    sendButton.style.display = 'none';
                    abortButton.style.display = 'block';
                } else {
                    sendButton.style.display = 'block';
                    abortButton.style.display = 'none';
                }
            }
        }

    } catch (error) {
        console.error('An error occurred during script execution:', error);
    }
});

// 回退以确保即使DOMContentLoaded已触发也已添加按钮
if (document.readyState === 'complete' || document.readyState === 'interactive') {
    setTimeout(function () {
        let event = new Event('DOMContentLoaded');
        document.dispatchEvent(event);
    }, 1);
}

